package com.bto.solar.work.fdd.client;

import com.bto.solar.work.common.BizException;
import com.bto.solar.work.constant.Constants;
import com.fasc.open.api.bean.base.BaseRes;
import com.fasc.open.api.bean.common.Field;
import com.fasc.open.api.bean.common.FieldTextSingleLine;
import com.fasc.open.api.bean.common.OpenId;
import com.fasc.open.api.enums.common.IdTypeEnum;
import com.fasc.open.api.exception.ApiException;
import com.fasc.open.api.v5_1.client.TemplateClient;
import com.fasc.open.api.v5_1.req.signtask.AddDocInfo;
import com.fasc.open.api.v5_1.req.signtask.CancelSignTaskCreateReq;
import com.fasc.open.api.v5_1.req.template.DocTemplateDetailReq;
import com.fasc.open.api.v5_1.req.template.DocTemplateFillValuesReq;
import com.fasc.open.api.v5_1.res.template.DocTemplateDetailRes;
import com.fasc.open.api.v5_1.res.template.DocTemplateFillValuesRes;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class FddTemplateClient {

    @Value("${fdd.template.qy.doc-id}")
    private String qyDocId;
    @Value("${fdd.template.qy.doc-template-id}")
    private String qyDocTemplateId;
    @Value("${fdd.template.qy.doc-template-name}")
    private String qyDocTemplateName;
    @Value("${fdd.template.zf.doc-id}")
    private String zfDocId;
    @Value("${fdd.template.zf.doc-template-id}")
    private String zfDocTemplateId;
    @Value("${fdd.template.zf.doc-template-name}")
    private String zfDocTemplateName;
    @Value("${fdd.template.zf.doc-file-id}")
    private String zfDocFileId;
    @Value("${fdd.open-crop-id}")
    private String openCorpId;

    @Autowired
    private FddBaseClient fddBaseClient;

    /**
     * 创建模板管理客户端
     */
    public TemplateClient getFddTemplateClient() {
       return new TemplateClient(fddBaseClient.getFddOpenApiClient());
    }

    /**
     * 查询文档模板详情的控件列表 --- 接口
     */
    public List<Field> getDocTemplateDetail(String docTemplateId)  {
        try{
            DocTemplateDetailReq docTemplateDetailReq = new DocTemplateDetailReq();
            docTemplateDetailReq.setAccessToken(fddBaseClient.getFddAccessToken());
            //（可选）模板归属方，主体类型IdTypeEnum。如果未指定，则表示查询应用的模板。如果指定，则表示查询企业主体有权访问的模板（主体模板和应用模板）
            docTemplateDetailReq.setOwnerId(OpenId.getInstance(IdTypeEnum.CORP.getCode(),  openCorpId));
            //文档模板id。
            docTemplateDetailReq.setDocTemplateId(docTemplateId);
            BaseRes<DocTemplateDetailRes> res = getFddTemplateClient().getDocTemplateDetail(docTemplateDetailReq);
            fddBaseClient.isResultSuccess(res, "获取法大大的文档模板详情失败");
            return res.getData().getDocFields();
        } catch (ApiException e) {
            throw new BizException("获取法大大的文档模板详情失败");
        }

    }


    /**
     * 获取个人信息使用授权书，签署文件
     */
    public AddDocInfo getDoc() {
        AddDocInfo docInfo = new AddDocInfo();
        //指定文档序号。
        docInfo.setDocId(qyDocId);
        //指定在本签署任务中的文档名称。
        docInfo.setDocName(qyDocTemplateName);
        //（可选）文档模板ID。
        docInfo.setDocTemplateId(qyDocTemplateId);
        //（可选）可在文档中添加一些控件。注：当前仅支持添加签章控件。
        docInfo.setDocFields(getDocTemplateDetail(qyDocTemplateId));
        return docInfo;
    }

    /**
     * 构建 自行上传的作废协议文档
     */
    public CancelSignTaskCreateReq.CancelDoc getCancelDoc(String idNumber) {
        CancelSignTaskCreateReq.CancelDoc cancelDoc = new CancelSignTaskCreateReq.CancelDoc();
        cancelDoc.setDocId(zfDocId);
        cancelDoc.setDocName(zfDocTemplateName);
        cancelDoc.setDocFileId(zfDocFileId);
        List<Field> fields = getDocTemplateDetail(zfDocTemplateId);
        fields.forEach(field -> {
            if ("text_single_line".equals(field.getFieldType())) {
                FieldTextSingleLine fieldTextSingleLine = new FieldTextSingleLine();
                fieldTextSingleLine.setDefaultValue(idNumber);
                field.setFieldTextSingleLine(fieldTextSingleLine);
            }
        });
        cancelDoc.setDocFields(fields);
        return cancelDoc;
    }

    /**
     * 模板生成文件
     */
    public DocTemplateFillValuesRes getTemplateToFile (String idCardNumber) throws ApiException {
        DocTemplateFillValuesReq req = new DocTemplateFillValuesReq();
        req.setAccessToken(fddBaseClient.getFddAccessToken());
        req.setDocTemplateId(zfDocTemplateId);
        req.setFileName(zfDocTemplateName);
        List<DocTemplateFillValuesReq.DocFieldValue> docFieldValueList = new ArrayList<>();
        getDocTemplateDetail(zfDocTemplateId).forEach(field -> {
            if ("text_single_line".equals(field.getFieldType())) {
                DocTemplateFillValuesReq.DocFieldValue docFieldValue = new DocTemplateFillValuesReq.DocFieldValue();
                docFieldValue.setFieldId(field.getFieldId());
                docFieldValue.setFieldName(field.getFieldName());
                docFieldValue.setFieldValue(idCardNumber);
                docFieldValueList.add(docFieldValue);
            }
        });
        req.setDocFieldValues(docFieldValueList);
        return getFddTemplateClient().docTemplateFillValues(req).getData();
    }

    public String getQyDocId() {
        return qyDocId;
    }

    public String getZfDocId() {
        return zfDocId;
    }

    public String getZfDocTemplateId() {
        return zfDocTemplateId;
    }
}
